let mqtt = require('mqtt')
let client = {}
export default {
    launch(url) {
        client = mqtt(url, {
            clean: true,
            connectTimeout: 10000,
            // Auth
            clientId: 'vue-front-'+Math.floor(Math.random()*1000000),
            username: '99999',
            password: '123456',
        })
    },
    message(_topic, callback) {
        client.on('message', (topic, message) => {
            if (_topic === topic) {
                callback(topic, message)
            }
        })
    },
    end() {
        client.end()
    },
    subscribe(topic) {
        client.subscribe(topic, {
            qos: 0
        })
        console.log('subscribe:', topic)
    },
    publish(topic, message) {
        client.publish(topic, JSON.stringify(message), {
            qos: 1
        })
    }
}